package com.uaroadshow.finale.web.controller.api;

import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.uaroadshow.entity.trade.Product;
import com.uaroadshow.entity.user.User;
import com.uaroadshow.entity.user.UserCourse;
import com.uaroadshow.entity.user.UserInfo;
import com.uaroadshow.finale.handler.SmsHandler;
import com.uaroadshow.finale.service.DataService;
import com.uaroadshow.finale.service.UserCourseService;

/**
 * 个人中心
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/api/profile")
public class ProfileApiController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProfileApiController.class);
    
    @Autowired
    @Qualifier("dataService")
    private DataService<User> userService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<UserInfo> userInfoService;
    
    @Autowired
    private UserCourseService userCourseService;
    
    @Autowired
    private SmsHandler smsHandler;
    
    /**
     * 个人中心
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult index(@RequestParam("unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            // 1. load user
            User user = userService.load(User.class, "unionid", unionid);
            
            // 2. load user info
            UserInfo userInfo = userInfoService.load(UserInfo.class, "user", user);
            
            // 3. count user_course
            List<UserCourse> courses = userCourseService.list(user);
            
            httpResult.success().data("user", user)
                                .data("userInfo", userInfo)
                                .data("courseSize", courses.size())
                                .message("查询成功");
            
        } catch (Exception e) {
            logger.error("#index() - load user failed, exception=[{}]", e);
            httpResult.fail("500").message("查询失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 用户课程列表
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/courses", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult listCourse(@RequestParam("unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // 1. load user
            User user = userService.load(User.class, "unionid", unionid);
            if (user == null) {
                throw BusinessException.newInstance("1", "用户不存在");
            }
            
            // 2. list user course
            List<UserCourse> courses = userCourseService.list(user);
            Map<String, UserCourse> coursesMap = CollectionUtils.constructMapValue(courses, "product.id");
            @SuppressWarnings("unchecked")
            List<Product> products = CollectionUtils.extractPropertyList(courses, "product");
            
            httpResult.success().data("courses", courses)
                                .data("coursesMap", coursesMap)
                                .data("products", products)
                                .data("courseLength", courses.size())
                                .message("查询成功");
            
        } catch (BusinessException e) {
            logger.error("#listCourse() - list course failed, business exception=[{}]", e);
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("#listCourse() - list course failed, exception=[{}]", e);
            httpResult.fail("500").message("查询失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 课程详情
     * 
     * @param unionid
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/courses/{courseId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult loadCourse(@RequestParam("unionid") String unionid,
                                 @PathVariable("courseId") Long courseId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            // 1. load user_course
            UserCourse userCourse = userCourseService.load(UserCourse.class, courseId);
            
            // 2. load user_info
            UserInfo userInfo = userInfoService.load(UserInfo.class, "user", userCourse.getUser());
            
            httpResult.success().data("product", userCourse.getProduct())
                                .data("user", userCourse.getUser())
                                .data("userInfo", userInfo)
                                .data("order", userCourse.getOrder())
                                .data("userCourseCode", userCourse.getCode())
                                .message("查询成功");
            
        } catch (BusinessException e) {
            logger.error("#loadCourse() - load course failed, business exception=[{}]", e);
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("#loadCourse() - load course failed, exception=[{}]", e);
            httpResult.fail("500").message("查询失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 绑定手机
     * 
     * @param unionid
     * @param mobile
     * @param code
     * @param token
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult auth(@RequestParam("unionid") String unionid,
                           @RequestParam("mobile") String mobile,
                           @RequestParam("code") String code,
                           @RequestParam("token") String token) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            // 1. check sms code
            boolean valid = smsHandler.checkVerifyCode(mobile, code, token);
            if (!valid) {
                return httpResult.fail("1").message("短信验证码错误");
            }
            
            // 2. bind mobile
            User user = userService.load(User.class, "unionid", unionid);
            userService.update(user.editMobile(mobile));
            
            httpResult.success().message("绑定成功");
            
        } catch (Exception e) {
            logger.error("#auth() - auth failed, exception=[{}]", e);
            httpResult.fail("500").message("绑定失败");
        }
        
        return httpResult;
        
    }
    
}
